 <?php

require_once 'BlogpostsView.php';
require_once 'BlogpostsHandler.php';
require_once 'LoginHandler.php';

class BlogpostsController{

	private $message = "";
	private $ret = "";
	private $error = FALSE;	
	
	public function DoControll(Database $db){
		$blogpostsView = new BlogpostsView();
		$blogpostsHandler = new BlogpostsHandler($db);
		$loginHandler = new LoginHandler($db);
		
		
		//Endast om admin är inloggad ska formuläret för att skriva nya blogginlägg synas.
		if($loginHandler->UserIsAdmin() === true){
			$this->ret .= $blogpostsView->BlogPost();
		}
		else{
			$this->ret .= $blogpostsView->NotLoggedInAsAdmin();
		}
		
		if($blogpostsView->TriedToPost()){
			
			//Kollar så att administratören har skrivit någon titel.
			if($blogpostsHandler->titleIsEmpty($blogpostsView->GetTitle())){
				$this->message .=$blogpostsView->Message(BlogpostsView::TITLE_IS_EMPTY);
				$this->error = TRUE;
			}
			//Kollar så att admin har skrivit något inlägg.
			if($blogpostsHandler->postIsEmpty($blogpostsView->GetPost())){
				$this->message .=$blogpostsView->Message(BlogpostsView::POST_IS_EMPTY);
				$this->error = TRUE;
			}
			//Kollar så att admin har skrivit författare.
			if($blogpostsHandler->authorIsEmpty($blogpostsView->GetAuthor())){
				$this->message .=$blogpostsView->Message(BlogpostsView::AUTHOR_IS_EMPTY);
				$this->error = TRUE;
			}
			//Validerar så att ingen html eller javascript går igenom.
			if($blogpostsHandler->validateTitle($blogpostsView->GetTitle()) === FALSE){
				$this->message .=$blogpostsView->Message(BlogpostsView::NO_HACK);
				$this->error = TRUE;
			}
			
			if($blogpostsHandler->validatePost($blogpostsView->GetPost()) === FALSE){
				$this->message .=$blogpostsView->Message(BlogpostsView::NO_HACK);
				$this->error = TRUE;
			}
			
			if($blogpostsHandler->validateAuthor($blogpostsView->GetAuthor()) === FALSE){
				$this->message .=$blogpostsView->Message(BlogpostsView::NO_HACK);
				$this->error = TRUE;
			}
			
			if($this->error === FALSE){
				//$blogpost = new blogpost($blogpostsView->GetTitle(), $blogpostsView->GetPost(), $blogpostsView->GetAuthor())
				if($blogpostsHandler->CreateBlogposts($blogpostsView->GetTitle(), $blogpostsView->GetPost(), $blogpostsView->GetAuthor())){ //skicka in $blogpost
					$this->message .=$blogpostsView->Message(BlogpostsView::BLOGPOST_CREATED);
				
				}
			}
		}
		return $this->ret . $this->message;
		
	}
}
